package com.zbbt.sportslottery.ui.activity;

import java.util.ArrayList;
import java.util.List;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.gc.materialdesign.views.ProgressBarCircularIndetermininate;
import com.google.gson.JsonObject;
import com.zbbt.sportslottery.R;
import com.zbbt.sportslottery.app.App;
import com.zbbt.sportslottery.app.ServerConfig;
import com.zbbt.sportslottery.bean.IndexFunBean;
import com.zbbt.sportslottery.bean.LotteryShopData;
import com.zbbt.sportslottery.bean.SuperResult;
import com.zbbt.sportslottery.bean.DialogBean.OnDialogClickListener;
import com.zbbt.sportslottery.net.TypeGsonHttpHandler;
import com.zbbt.sportslottery.net.ZbHttpClient;
import com.zbbt.sportslottery.ui.adapter.LotteryShopAdapter;
import com.zbbt.sportslottery.ui.widget.SimpleCustomDialog;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout;
import com.zbbt.sportslottery.ui.widget.swipe.SwipeRefreshLayout.OnRefreshListener;
import com.zbbt.sportslottery.util.DialogUtil;
import com.zbbt.sportslottery.util.LogUtil;
import com.zbbt.sportslottery.util.ToastUtil;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class LotteryShopActivity extends SimpleBaseActivity {

	private LocationClient location;
	private MyLocationListenner myLocationListenner = new MyLocationListenner();
	private Double Longitude = 0.0;// 定位获取经度
	private Double Latitude = 0.0;// 定位获取纬度
	private boolean isFirstLoc = true;// 是否首次定位
	private TextView exception_tx;
	private int page_number = 1;
	private int page_size = 10;
	private LotteryShopAdapter mAdapter;
	private SwipeRefreshLayout refreshLayout;
	private ListView mListView;
	private ProgressBarCircularIndetermininate progressBar;
	private List<LotteryShopData> shopDatas = new ArrayList<LotteryShopData>();
	private boolean isShow = false;// 是否显示
	private boolean isGetMore = false;// 请求形式，true=翻页／false=当前页
	private boolean hasMore = true;// 是否还有下一页
	private boolean isOnPause = false;// 是否显离开本页
	private boolean isHttpFinish = true;// 是否完成一次网络请求
	private LinearLayout error_linear;// 无网
	private LinearLayout none_view_layout;// 无数据
	private View buttom_lLayout;// 底部
	private int openNum;//是否打开

	@Override
	protected void onActivityCreated(Bundle savedInstanceState) {
		setContentView(R.layout.fragment_lottry_shop);
		Intent intent = getIntent();
		openNum = intent.getIntExtra("isOpen", 1);
		LogUtil.printD("stringExtra", openNum+"");
		
	}

	@Override
	protected void initView() {
		buttom_lLayout=View.inflate(context,R.layout.fragment_bottom_layout , null);
		final TextView bottom_tx = (TextView) buttom_lLayout.findViewById(R.id.bottom_tx);
		buttom_lLayout.setVisibility(View.GONE);
		progressBar = (ProgressBarCircularIndetermininate) findViewById(R.id.progressBarCircularIndetermininate);
		// 初始化视图
		refreshLayout = (SwipeRefreshLayout) findViewById(R.id.lottry_swipe_container);
		mListView = (ListView) findViewById(R.id.notice_listview);
		exception_tx = (TextView) findViewById(R.id.exception_tx);
		error_linear = (LinearLayout) findViewById(R.id.error_layout);
		mListView.addFooterView(buttom_lLayout);
		if (openNum==1) {
			mAdapter = new LotteryShopAdapter(context, shopDatas);
			mAdapter.setOnBottomClickListener(new LotteryShopAdapter.OnBottomClickListener() {

				@Override
				public void onBottomClick() {
					buttom_lLayout.setVisibility(View.VISIBLE);
					if (hasMore == true) {
						page_number++;
						isGetMore = true;
						inithttpData();
						refreshLayout.setRefreshing(true);
					}else {
						bottom_tx.setText("暂无更多数据");
					}
				}
			});
			mListView.setAdapter(mAdapter);
			mListView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					Intent intent = new Intent(LotteryShopActivity.this, LotteryShopMapActivity.class);
					LotteryShopData lotteryShopData = shopDatas.get(position);
					String address = lotteryShopData.getAddress();// 地址
					String coordinate = lotteryShopData.getLatitude() + "," + lotteryShopData.getLongitude();// 坐标
					intent.putExtra("address", address);
					intent.putExtra("coordinate", coordinate);
					startActivity(intent);
				}
			});

			refreshLayout.setOnRefreshListener(new OnRefreshListener() {

				@Override
				public void onRefresh() {
					if (isHttpFinish) {
						page_number = 1;
						isGetMore = false;
						initLocData();
						exception_tx.setVisibility(View.GONE);
					}
				}

			});
			progressBar.setVisibility(View.VISIBLE);
			initLocData();
		} else {
			none_view_layout = (LinearLayout) findViewById(R.id.none_view_layout);
			none_view_layout.setVisibility(View.VISIBLE);
			progressBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		isOnPause = false;
	}

	@Override
	public void onPause() {
		super.onPause();
		if (location != null) {
			location.stop();
		}
		isOnPause = true;
		progressBar.setVisibility(View.GONE);

	}

	/**
	 * 
	 * @MethodName:initLocData
	 * @Description: 定位初始化后，两秒后判断经纬度有没拿到。没拿到弹窗，拿到请求服务器
	 * @author：gaomingshuo
	 * @date：2015-1-23 下午3:00:17 void
	 */

	public void initLocData() {
		shopDatas.clear();
		mAdapter.notifyDataSetChanged();
		isHttpFinish = false;
		initLoc();
		new Handler().postDelayed(new Runnable() {
			public void run() {
				whetherHave();
			}
		}, 3000);
	}

	/**
	 * 
	 * @MethodName:initLoc
	 * @Description: TODO
	 * @author：gaomingshuo
	 * @date：2015-1-23 下午3:00:00 void
	 */
	public void initLoc() {
		isFirstLoc = true;
		location = new LocationClient(this);
		location.registerLocationListener(myLocationListenner);
		LocationClientOption option = new LocationClientOption();// 打开经纬度坐标
		option.setLocationMode(LocationMode.Hight_Accuracy);// 高精度模式
		option.setOpenGps(true);// 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setScanSpan(1000);
		location.setLocOption(option);
		location.start();
	}

	/**
	 * 
	 * @MethodName:whetherHave
	 * @Description: TODO
	 * @author：gaomingshuo
	 * @date：2015-1-23 下午2:59:29 void
	 */
	public void whetherHave() {
		if (Latitude == 4.9E-324 || Latitude == 0.0) {
			progressBar.setVisibility(View.GONE);
			if (isShow == false) {
				if (!isOnPause) {
					initLocation();// 提示弹窗
				} else {
					// 直接跳转Activity（LoginActivity），会执行
					exception_tx.setVisibility(View.VISIBLE);
					exception_tx.setText("请下拉刷新");
				}
			} else {
				exception_tx.setVisibility(View.VISIBLE);// 提示打开软件
				exception_tx.setText("位置还是无法获取?查看是否被安全软件关闭权限或者重新打开软件");
			}
			isHttpFinish = true;
			progressBar.setVisibility(View.GONE);
			refreshLayout.setRefreshing(false);
		} else {
			inithttpData();
			exception_tx.setVisibility(View.GONE);
		}
	}

	/**
	 * 
	 * @MethodName: initLocation
	 * @Description: 没拿到经纬度，弹窗提示
	 * @author: gaomingshou
	 * @date: 2015年1月23日 下午14:31:98
	 */
	private void initLocation() {
		SimpleCustomDialog showConfirmDialog = DialogUtil.showConfirmDialog(context, "提示", "查看网点需要开启GPS，确定是否开启", "去设置", "已开启", new OnDialogClickListener() {

			@Override
			public boolean onClick(View v) {
				Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
				startActivity(callGPSSettingIntent);
				isShow = true;
				exception_tx.setVisibility(View.VISIBLE);
				exception_tx.setText("确定GPS已开启，下拉刷新");
				return false;
			}
		}, new OnDialogClickListener() {

			@Override
			public boolean onClick(View v) {
				isShow = true;
				progressBar.setVisibility(View.VISIBLE);
				initLocData();
				if (!(Latitude == 4.9E-324 || Latitude == 0.0)) {
					inithttpData();
				}
				return false;
			}
		});
		// 当点击弹窗空白的时候给出的提示。
		showConfirmDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				exception_tx.setVisibility(View.VISIBLE);
				exception_tx.setText("请下拉刷新");
			}
		});

	}

	@Override
	protected void setListener() {
		error_linear.setOnClickListener(this);
	}

	@Override
	protected void onClickEvent(View v) {
		switch (v.getId()) {
		case R.id.error_layout:
			progressBar.setVisibility(View.VISIBLE);
			error_linear.setVisibility(View.GONE);
			initLocData();
			exception_tx.setVisibility(View.GONE);
			break;

		default:
			break;
		}
	}

	public void inithttpData() {
		JsonObject jsonObject = new JsonObject();
		String coordinateStr = Longitude + "," + Latitude;
		jsonObject.addProperty("coordinate", coordinateStr);
		jsonObject.addProperty("curPage", page_number);
		jsonObject.addProperty("pageSize", page_size);
		jsonObject.addProperty("ticketType", 1);
		jsonObject.addProperty("distance", 10000000.0);
		LogUtil.printD("DemoLog", coordinateStr);
		ZbHttpClient.postNewApi(ServerConfig.API_TZZD, jsonObject, new TypeGsonHttpHandler<SuperResult<LotteryShopData>>() {
			@Override
			public void onSuccess(SuperResult<LotteryShopData> data) {
				isHttpFinish = true;
				progressBar.setVisibility(View.GONE);
				ArrayList<LotteryShopData> data2 = data.getData();
				if (data2.size() == 0) {
					refreshLayout.setRefreshing(false);
					ToastUtil.showShort("没有数据");
					error_linear.setVisibility(View.VISIBLE);
					return;
				}
				if (data.getData() != null) {
					if (!isGetMore) {
						shopDatas.clear();
					}
					shopDatas.addAll(data.getData());
					mAdapter.notifyDataSetChanged();
					refreshLayout.setRefreshing(false);
				} else {
					hasMore = false;
				}
			}

			@Override
			public void onFailure(String errorCode, String errorMsg) {
				isHttpFinish = true;
				progressBar.setVisibility(View.GONE);
				refreshLayout.setRefreshing(false);
				error_linear.setVisibility(View.VISIBLE);
			}
		});
	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (isFirstLoc) {
				// 首次定位，拿到经度纬度
				isFirstLoc = false;
				Latitude = location.getLatitude();
				Longitude = location.getLongitude();
				LogUtil.printI(TAG, "经度" + Latitude + "===纬度" + Longitude);

			}
		}
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

}
